<script>
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import {getOrderDetails, getUserOrderList, productOrdersPay} from "@/api/mall";

export default {
  name: "payment",
  components: {HzSafeArea},
  data() {
    return {
      paymentInfo: {
        orderId: '',
        orderNo: '',
        totalAmount: 0,
        totalPrice: 0,
        productName: '',
        createTime: "",
        wxJsApiParam: null,
        productSpecStr: ''
      },
      isLoading: false,
      delta: 1
    }
  },
  onLoad(options) {
    // 设置导航栏标题
    uni.setNavigationBarTitle({title: this.$t('payment.title')});
    // 获取订单ID
    if (options && options.id) {
      console.log(options.id)
      // 获取订单ID
      this.paymentInfo.orderId = options.id;
      console.log('获取到订单ID:', this.paymentInfo.orderId);
      this.delta = parseInt(options.delta)
      // 获取订单详情
      this.getOrderDetail();
    } else {
      console.error('未获取到订单ID');
      uni.showToast({
        title: this.$t('payment.incompleteOrder'),
        icon: 'none',
        duration: 2000
      });
    }
  },
  computed:{
    safeAreaTop(){
      return this.$store.state.app.wxMenuClient.top
    }
  },
  methods: {
    // 获取订单详情
    async getOrderDetail() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });

        const { Data } = await getUserOrderList({OrderId: this.paymentInfo.orderId})
        console.log('订单数据:', Data);

        if (Array.isArray(Data) && Data.length > 0) {
          // 新的数据格式是数组，取第一项
          const orderData = Data[0];

          // 设置订单基本信息
          this.paymentInfo.orderNo = orderData.OrdersANO || '';
          this.paymentInfo.totalPrice = orderData.OriginalPriceTotal || 0;
          this.paymentInfo.totalAmount = orderData.SalePriceTotal || 0;
          this.paymentInfo.createTime = orderData.AddTime || '';

          // 获取商品名称信息
          if (orderData.OrdersOnlineInfoViewList && orderData.OrdersOnlineInfoViewList.length > 0) {
            // 判断是否为套票订单
            if (orderData.OrdersOnlineInfoViewList.length >= 2) {
              this.paymentInfo.productName = '套餐产品';
            } else {
              // 单个商品订单
              const firstProduct = orderData.OrdersOnlineInfoViewList[0];
              this.paymentInfo.productName = firstProduct.ProductName || '未知商品';
            }
          } else {
            this.paymentInfo.productName = '未知商品';
          }

          // 获取产品规格信息
          if (orderData.OrdersOnlineInfoViewList && orderData.OrdersOnlineInfoViewList.length > 0) {
            const firstProductSpec = orderData.OrdersOnlineInfoViewList[0].ProductSpecStr;
            this.paymentInfo.productSpecStr = firstProductSpec || '';
          } else {
            this.paymentInfo.productSpecStr = '';
          }
        } else {
          // 兼容旧格式
          this.paymentInfo.orderNo = Data.ANO || '';
          this.paymentInfo.totalPrice = Data.OriginalPriceTotal || 0;
          this.paymentInfo.totalAmount = Data.SalePriceTotal || 0;
          this.paymentInfo.createTime = Data.AddTime || '';
        }

        uni.hideLoading();
      } catch (error) {
        console.error('获取订单信息失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '获取订单信息失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    // 处理支付
    handlePayment() {
      if (this.isLoading) return;

      // 验证支付信息
      if (!this.paymentInfo.orderId) {
        uni.showToast({
          title: this.$t('payment.incompleteOrder'),
          icon: 'none'
        });
        return;
      }

      this.isLoading = true;
      uni.showLoading({
        title: this.$t('payment.processing'),
        mask: true
      });

      // 然后使用返回的支付参数
      productOrdersPay({ OrdersOnLineId: this.paymentInfo.orderId }).then(res => {
        if (!res.Data || typeof res.Data !== 'object') {
          console.error('支付参数异常:', res);
          this.isLoading = false;
          uni.hideLoading();
          uni.showToast({
            title: this.$t('payment.invalidParams'),
            icon: 'none',
            duration: 2000
          });
          return;
        }

        let paymentParams;
        try {
          // 尝试解析支付参数
          paymentParams = res.Data.WxJsApiParam ? JSON.parse(res.Data.WxJsApiParam) : null;
        } catch (error) {
          console.error('解析支付参数失败:', error);
          this.isLoading = false;
          uni.hideLoading();
          uni.showToast({
            title: this.$t('payment.parseError'),
            icon: 'none',
            duration: 2000
          });
          return;
        }

        // 如果没有支付参数，直接跳转订单页
        if (!paymentParams) {
          this.isLoading = false;
          uni.hideLoading();
          uni.showToast({
            title: this.$t('payment.noParams'),
            icon: 'none',
            duration: 2000
          });
          return;
        }

        // 调用微信支付
        uni.requestPayment({
          provider: 'wxpay',
          timeStamp: paymentParams.timeStamp,
          nonceStr: paymentParams.nonceStr,
          package: paymentParams.package,
          signType: paymentParams.signType,
          paySign: paymentParams.paySign,
          success: () => {
            uni.reLaunch({
              url: "/mall_subpages/goods/success?delta=" + this.delta + 1 + "&id=" + this.paymentInfo.orderId
            })
          },
          fail: (err) => {
            this.isLoading = false;
            uni.hideLoading();
            console.log('支付失败:', JSON.stringify(err));
            uni.showToast({
              title: this.$t('payment.cancelled'),
              icon: 'none',
              duration: 2000
            });
          }
        });
      }).catch(error => {
        console.error('支付接口调用失败:', error);
        this.isLoading = false;
        uni.hideLoading();
        uni.showToast({
          title: error.Msg || '支付接口调用失败',
          icon: 'none',
          duration: 2000
        });
      });
    },

    // 处理支付/预定成功
    handlePaymentSuccess(message) {
      this.isLoading = false;
      uni.hideLoading();
      uni.showToast({
        title: message,
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.reLaunch({
              url: '/mall_subpages/order/orderPack'
            });
          }, 2000);
        }
      });
    },

    // 返回上一页
    back() {
      uni.navigateBack({
        delta: this.delta
      });
    },

    // 格式化规格信息
    formatSpecStr(specStr) {
      if (!specStr) return '';
      return specStr.split('|').join(' ');
    }
  }
}
</script>

<template>
  <view class="payment-container" :style="{paddingTop: `calc(44px + 30rpx + ${safeAreaTop}px)`}">
    <u-navbar :title="$t('payment.title')" @leftClick="back"></u-navbar>
    <!-- 订单信息 -->
    <view class="order-info-card">
      <view class="order-title">{{$t('payment.orderInfo')}}</view>

      <view class="info-row">
        <text class="label">{{$t('payment.orderNo')}}</text>
        <text class="value">{{paymentInfo.orderNo || $t('detail.address')}}</text>
      </view>

      <view class="info-row">
        <text class="label">{{$t('payment.productName')}}</text>
        <text class="value">{{paymentInfo.productName || '未知商品'}}</text>
      </view>

      <!-- 添加规格信息行 -->
      <view class="info-row" v-if="paymentInfo.productSpecStr">
        <text class="label">{{$t('payment.specInfo')}}</text>
        <text class="value spec-value">{{formatSpecStr(paymentInfo.productSpecStr)}}</text>
      </view>

      <view class="info-row">
        <text class="label">{{$t('payment.orderTime')}}</text>
        <text class="value">{{paymentInfo.createTime || '未知时间'}}</text>
      </view>

      <view class="info-row payment-price">
        <text class="label">{{$t('payment.originalAmount')}}</text>
        <text class="amount">¥{{paymentInfo.totalPrice.toFixed(2)}}</text>
      </view>
      <view class="info-row payment-amount">
        <text class="label">{{$t('payment.paymentAmount')}}</text>
        <text class="amount">¥{{paymentInfo.totalAmount.toFixed(2)}}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-method-card">
      <view class="payment-title">{{$t('payment.paymentMethod')}}</view>

      <view class="payment-method-item">
        <view class="method-left">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250516/202505161908413831.png" mode="aspectFit" class="method-icon"></image>
          <text class="method-name">{{$t('payment.wechatPay')}}</text>
        </view>
        <view class="method-right">
          <image src="/static/icons/checked.png" mode="aspectFit" class="check-icon"></image>
        </view>
      </view>
    </view>

    <hz-safe-area background="#F5F6F7"></hz-safe-area>

    <!-- 底部支付按钮 -->
    <view class="bottom-bar">
      <view class="bottom-bar-inner">
        <view class="price-section">
          <text>¥</text>
          <text class="total-price">{{paymentInfo.totalAmount.toFixed(2)}}</text>
        </view>
        <view class="pay-btn" @click="handlePayment">
          <text>{{$t('payment.pay')}}</text>
        </view>
      </view>
      <hz-safe-area></hz-safe-area>
    </view>
  </view>
</template>

<style scoped lang="scss">
// 布局容器
.payment-container {
  padding: 30rpx;
  background-color: #F5F6F7;
  min-height: 100vh;
  padding-bottom: 180rpx;
}

// 订单信息卡片
.order-info-card, .payment-method-card {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-title, .payment-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
  position: relative;
  padding-left: 20rpx;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 10rpx;
    height: 30rpx;
    width: 6rpx;
    background-color: #498FFF;
    border-radius: 3rpx;
  }
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .label {
    font-size: 28rpx;
    color: #666;
  }

  .value {
    font-size: 28rpx;
    color: #333;

    &.spec-value {
      max-width: 60%;
      text-align: right;
      word-break: break-all;
      color: #666;
    }
  }

  &.payment-amount , &.payment-price{
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx dashed #f0f0f0;

    .label {
      font-size: 32rpx;
      font-weight: 500;
    }

    .amount {
      font-size: 36rpx;
      color: #FF6B31;
      font-weight: bold;
    }
  }

  &.payment-price{
    .amount {
      font-size: 36rpx;
      color: #333;
    }
  }
}

// 支付方式
.payment-method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;

  .method-left {
    display: flex;
    align-items: center;

    .method-icon {
      width: 60rpx;
      height: 60rpx;
      margin-right: 20rpx;
    }

    .method-name {
      font-size: 28rpx;
      color: #333;
    }
  }

  .method-right {
    .check-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }
}

// 底部栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFF;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .bottom-bar-inner {
    display: flex;
    height: 100rpx;
    align-items: center;
    padding: 0 30rpx;
    width: 100%;
  }

  .price-section {
    flex: 1;
    display: flex;
    align-items: baseline;
    color: #FF6B31;
    font-weight: bold;

    .total-price {
      font-size: 40rpx;
      margin-left: 6rpx;
    }
  }

  .pay-btn {
    background: linear-gradient(135deg, #FF6B31 0%, #FF4B31 100%);
    border-radius: 40rpx;
    height: 80rpx;
    padding: 0 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      color: #FFF;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
}
</style>
